package edu.tec.mty.core.modules;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
//import java.util.Vector;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Logger extends Thread {

	private PrintWriter printer;
	private String user;
	private boolean running = true;
	private final Lock lock = new ReentrantLock();
	private final Condition write = lock.newCondition();
	private boolean writing = false;
	private boolean closing = false;
	private String text;
	
	public Logger(String filename, String user) {
		this.user = user;
		try {
			this.printer = new PrintWriter(new BufferedWriter(new FileWriter(filename + user)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void write(String message) {
		this.lock.lock();
		this.text = Long.toString(Game.GAME_TIME) +" >> " + message;
		this.writing = true;
		this.write.signal();
		this.lock.unlock();
	}
	
	public void write(Object obj, String message) {
		this.lock.lock();
		this.text = Long.toString(Game.GAME_TIME) + ": " +
					this.user + " > " +
					obj.getClass().getName() + " > " +
					message;
		//System.out.println(this.text);		
		this.writing = true;
		this.write.signal();
		this.lock.unlock();
	}
	
	public void shutdown() {
		this.lock.lock();
		this.running = false;
		this.closing = true;
		this.writing = true;
		this.write.signal();
		this.lock.unlock();
	}
	
	@Override
	public void run() {
		while(this.running) {
			this.lock.lock();
			try {
				while(!this.writing) {
					this.write.await();
				}
			} catch (Exception e) {
				System.err.println(e);
			}
			if (!this.closing) {
				this.printer.println(this.text);
			}
			this.writing = false;
			this.lock.unlock();
		}
		this.printer.flush();
		this.printer.close();
		if (this.printer.checkError()) {
			System.out.println("Error");
		}
		System.out.println("Logger closed");
	}
	
	//Test
	
	/*public static void main(String[] args) {
		Logger log = new Logger("test", "user");
		log.start();
		log.setGlobalTime(100);
		log.write(log, "test 1");
		try {
			Thread.sleep(1000);
		} catch (Exception e) {
			
		}
		log.shutdown();
	}*/
}
